//
//  HMOAuthViewController.swift
//  Faner_Weibo
//
//  Created by 范英强 on 16/1/28.
//  Copyright © 2016年 范英强. All rights reserved.
//

import UIKit
import SVProgressHUD
let APP_KEY = "2435105329"
let APP_SECRET = "fbf603b59f283d50896ac2807615f571"
let REDIRECT_URL = "http://www.itheima.com/"


class HMOAuthViewController: UIViewController,UIWebViewDelegate {
    
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        
        return webView
    }()
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APP_KEY)&redirect_uri=\(REDIRECT_URL)"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
    }
    
    // MARK: - 添加控件
    
    private func setupUI(){
        navigationItem.title = "微博登陆"
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "取消", target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem( title: "自动填充", target: self, action: "oauthFull")
    }
    
//    // MARK: - 请求数据
//    private func loadAccessToken(code: String){
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        let params = [
//            "client_id" : APP_KEY,
//            "client_secret" : APP_SECRET,
//            "grant_type" : "authorization_code",
//            "code" : code,
//            "redirect_uri": REDIRECT_URL
//        ]
//        HMNetWorkTools.sharedTools.request(.POST, url: urlString, params: params) { (response, error) -> () in
//            if error != nil{
//                print("请求失败\(error)")
//                return
//            }
//            
//            guard let dict =  response as? [String : AnyObject] else{
//                print("不是一个字典")
//                return
//            }
//            let account = HMUserAccount(dict: dict)
//            self.loadUserInfo(account)
//        }
//        
//    }
//    
//    //请求用户的数据
//    private func loadUserInfo(account: HMUserAccount){
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        let params = [
//            "access_token": account.access_token!,
//            "uid": account.uid!
//        ]
//        HMNetWorkTools.sharedTools.request(.GET, url: urlString, params: params) { (response, error) -> () in
//            if error != nil{
//                print("发送请求失败\(error)")
//                return
//            }
//            
//            guard let dict = response as? [String : AnyObject] else{
//                print("不是一个字典")
//                return
//            }
//            account.avatar_large = dict["avatar_large"] as? String
//            account.screen_name = dict["screen_name"] as? String
//            account.saveAccount()
//        }
//        
//    }
    
    // MARK: - 执行逻辑
    @objc private func dismiss(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func oauthFull(){
        let jsString = "document.getElementById('userId').value='18911412662';document.getElementById('passwd').value='19880828'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
}

// MARK: - webView delegate
extension HMOAuthViewController{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
       // print(request.URL)
        
        guard let url = request.URL?.absoluteString else{
            return true
        }
        
        if !url.hasPrefix(REDIRECT_URL){
            return true
        }
        
        print( request.URL)
        let code = request.URL!.query!.substringFromIndex("code=".endIndex)
      //  loadAccessToken(code)
        
        HMUserAccountViewModel.sharedAccount.loadAccessToken(code) { (isSuccess) -> () in
            SVProgressHUD.dismiss()
            if !isSuccess{
                SVProgressHUD.showErrorWithStatus("网络异常,登陆失败")
                return
            }
            
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                //发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootVcNotification, object: nil)
            })
           
            
            print("请求成功")
        }
        return false
    }
    
}
